package com.dgty.dg_common.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.dgty.dg_common.R
import com.dgty.dg_common.base.BaseActivity
import com.dgty.dg_common.databinding.ActivityWebBinding
import com.dgty.dg_common.util.Constants
import com.dgty.dg_common.util.StatusUtil
import me.jessyan.autosize.internal.CancelAdapt
import wendu.webviewjavascriptbridge.WVJBWebView
import wendu.webviewjavascriptbridge.WVJBWebView.*
import java.net.URLDecoder


/**
 * Title: WebActivity.kt
 * Description:
 * Created DateTime: 2023-02-08
 * Created by xxl.
 */
@Route(path = Constants.PATH_WEB)
@SuppressLint("SetJavaScriptEnabled")
class GameWebActivity : BaseActivity<ActivityWebBinding>(), CancelAdapt {

    lateinit var web: WebView

    override fun getLayoutID(): Int {
        return R.layout.activity_web
    }


    override fun initView() {
        if (intent == null) {
            return
        }


//        // 控制状态栏
//        StatusUtil.setBaseStatusBar(this)
        val t = intent.getStringExtra(Constants.WEB_TITLE)
        val o = intent.getIntExtra(Constants.WEB_DIRECTION, 0)
        val l = intent.getStringExtra(Constants.WEB_LINK).toString()

        Log.d(TAG, "xxlt: $t")
        Log.d(TAG, "xxlurl: $l")
        Log.d(TAG, "xxldirection: $o")

        //游戏横竖屏 1横屏 2竖屏
        if (o == 1 && this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {//设置横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        if (o == 2 && this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {//设置竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        immersionBarDark(true)
//        val window: Window = getWindow()
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
//        ScreenUtils.setFullScreen(this@WebActivity)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        // 控制状态栏
        StatusUtil.setBaseStatusBar(this)
        mBind.imgBack.setOnClickListener { finish() }
        mBind.txWebTitle.text = t



        web = WVJBWebView(applicationContext)
        mBind.webContainer.addView(web)

        web.settings.javaScriptEnabled = true
        web.settings.loadWithOverviewMode = true
        web.settings.javaScriptEnabled = true
        web.settings.domStorageEnabled = true

        /*   (web as WVJBWebView).hasJavascriptMethod("echoHandler", WVJBMethodExistCallback { exist ->
               if (exist) {
                   Log.d("wvjsblog", "Javascript handler 'echoHandler' exist. ")
               }
           })*/

        setJs()

        (web as WVJBWebView).callHandler("showAlert", "Hi from Java to JS!")
        (web as WVJBWebView).callHandler("getCurrentPageUrl", null, WVJBResponseCallback<Any?>
        { data -> Log.d("wvjsblog", "Current WVJBWebView page URL is: %@$data") })

        web.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.d(TAG, "onPageStarted: ")
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.d(TAG, "onPageFinished: ")
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.d(TAG, "shouldOverrideUrlLoading: =====1")
                return true
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                Log.d(TAG, "shouldOverrideUrlLoading: =====2")
                if (!l.equals(request?.url)) {
                    Log.d(TAG, "shouldOverrideUrlLoading: =====3")
                    startActivity(
                        Intent(Intent.ACTION_VIEW, Uri.parse(request?.url.toString()))
                    )
                    return true
                }
                return false
            }
        }

        web.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                Log.d(TAG, "onProgressChanged: $newProgress")
                mBind.pb.progress = newProgress
                if (newProgress == 100) {
                    mBind.pb.visibility = View.GONE
                }
            }
        }

        web.loadUrl(l)

    }

    private fun setJs() {
        //关闭页面
        (web as WVJBWebView).registerHandler("closeWebView", object : WVJBHandler<Any, Any> {
            override fun handler(data: Any, callback: WVJBResponseCallback<Any>) {
                Log.d("wvjsblog", "closeWebView with: " + data.toString())
                callback.onResult(data)
                finish()
            }
        })
        //跳转训练营课程列表
        (web as WVJBWebView).registerHandler("jumpPage", object : WVJBHandler<Any, Any> {
            override fun handler(data: Any, callback: WVJBResponseCallback<Any>) {
                Log.d("wvjsblog", "jumpPage with: " + data.toString())
                callback.onResult(data)
                var decodeUrl = URLDecoder.decode("" + data, "utf-8")
//                {"router": "http://magic.cc/xxxx/router/trainingCourseList"}
                if (decodeUrl.contains("router/trainingCourseList")) {
                    ActivityHelper.startTrainList()
                }
            }
        })
    }

    override fun onDestroy() {
        LogUtils.d("xxlwebview", "onDestroy")
        mBind.webContainer.removeAllViews()
        web.clearHistory()
        web.destroy()
        super.onDestroy()
    }

    override fun initData() {

    }
}